package task;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * Creared with IntelliJ IDEA.
 * Description:
 * User:yxd
 * Date:2022-03-30
 * Time:0:20
 */
//表示一个任务
class MyTask implements Comparable<MyTask>{
    private Runnable runnable;
    private long time;
    //这里的时间表示时间间隔
    public MyTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }
    //执行任务
    public void run(){
        runnable.run();
    }
    //获得当前时间
    public long getTime(){
        return time;
    }
    //实现比较接口
    @Override
    public int compareTo(MyTask o){
        return (int)(this.time - o.time);//基于时间来比较
    }
}
//这里不一定是单线程的
class MyTimer{
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    //任务执行方法
    public void schedule(Runnable runnable,long time){
        MyTask task = new MyTask(runnable,time);
        queue.put(task);

        //放入成功一个就要唤醒一次wait看当前堆顶是不是要到了
        synchronized (locker){
            locker.notify();
        }

    }
    private Object locker = new Object();//类对象
    //构造方法
    public MyTimer(){
        //设置一个线程,让这个线程不断扫描堆顶将堆顶的元素取出来看一下是不是要到时间了
        Thread t = new Thread(()->{
            while (true){
                try {
                    MyTask task = queue.take();
                    long curtime = System.currentTimeMillis();
                    if(curtime < task.getTime()){
                        //时间还没到,再放回去
                        queue.put(task);
                        synchronized (locker){
                            locker.wait(task.getTime() - curtime);//等待当前所剩的时间
                        }
                    }else{
                        //时间到了,该执行了
                        task.run();

                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });
        t.start();

    }
}
public class Practice_4 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer");
            }
        },3000);
        System.out.println("main");
    }
}
